package com.kkb.mybatis.framework.executor;

import com.kkb.mybatis.framework.config.BoundSql;
import com.kkb.mybatis.framework.config.Configuration;
import com.kkb.mybatis.framework.config.MappedStatement;
import com.kkb.mybatis.framework.sqlsource.SqlSource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SimpleExecutor、ReuseExecutor、BatchExecutor这三个类都要走该类的以及缓存流程
 */
public abstract class BaseExecutor implements Executor {

    //一级缓存
    private Map<String, List<Object>> oneLevelCache = new HashMap<>();

    @Override
    public <T> List<T> query(Configuration configuration, MappedStatement mappedStatement, Object param) {

        SqlSource sqlSource = mappedStatement.getSqlSource();
        BoundSql boundSql = sqlSource.getBoundSql(param);
        //获取缓存的key
        String cacheKey = getCacheKey(boundSql);
        List<Object> list = oneLevelCache.get(cacheKey);

        if (list != null){
            return (List<T>) list;
        }

        //查询数据库
        List<Object> list1 = queryFromDataBase(configuration, mappedStatement,boundSql , param);
        oneLevelCache.put(cacheKey,list1);
        return (List<T>) list1;
    }

    protected abstract List<Object> queryFromDataBase(Configuration configuration, MappedStatement mappedStatement, BoundSql boundSql , Object param);


    private String getCacheKey(BoundSql boundSql) {
        //cache要做特殊处理

        return boundSql.getSql();
    }
}
